package com.hundsun.s3.mrs.core.endpoint;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * websocket终端启动器
 * @author chenji23607
 *
 */
public class EndPointStarter implements Runnable {
	
	private static final Logger LOG = LoggerFactory.getLogger(EndPointStarter.class);
	
	/**
	 * 最小端口
	 */
	private int minPort = 1024;
	
	/**
	 * 最大端口
	 */
	private int maxPort = 65532;
	
	/**
	 * 尝试次数
	 */
	private int tryCount = 30;
	

	public EndPointStarter(int tryCount) {
		super();
		this.tryCount = tryCount;
	}

	public EndPointStarter(int minPort, int maxPort, int tryCount) {
		super();
		this.minPort = minPort;
		this.maxPort = maxPort;
		this.tryCount = tryCount;
	}

	
	
	public void run() {
		int randomPort;
		CoreEndPoint endPoint = new CoreEndPoint();
		int i = 1;
		while(i<=tryCount) {
			randomPort = (int) (Math.random() * (maxPort-minPort) + minPort);
			LOG.info("第" + i + "次建立websocket服务尝试，端口号为"+randomPort);
			if(!endPoint.start(randomPort)) {
				i++;
			}
		}
		if(i == tryCount) {
			// 启动websocket失败
			LOG.error("websocket服务启动失败");
		}
	}
	
	public int getMinPort() {
		return minPort;
	}

	public void setMinPort(int minPort) {
		this.minPort = minPort;
	}

	public int getMaxPort() {
		return maxPort;
	}

	public void setMaxPort(int maxPort) {
		this.maxPort = maxPort;
	}

	public int getTryCount() {
		return tryCount;
	}

	public void setTryCount(int tryCount) {
		this.tryCount = tryCount;
	}

}
